{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4144c129",
   "metadata": {
    "origin_pos": 1
   },
   "source": [
    "# Automatic Differentiation\n",
    ":label:`sec_autograd`\n",
    "\n",
    "Recall from :numref:`sec_calculus` \n",
    "that calculating derivatives is the crucial step\n",
    "in all the optimization algorithms\n",
    "that we will use to train deep networks.\n",
    "While the calculations are straightforward,\n",
    "working them out by hand can be tedious and error-prone, \n",
    "and these issues only grow\n",
    "as our models become more complex.\n",
    "\n",
    "Fortunately all modern deep learning frameworks\n",
    "take this work off our plates\n",
    "by offering *automatic differentiation*\n",
    "(often shortened to *autograd*). \n",
    "As we pass data through each successive function,\n",
    "the framework builds a *computational graph* \n",
    "that tracks how each value depends on others.\n",
    "To calculate derivatives, \n",
    "automatic differentiation \n",
    "works backwards through this graph\n",
    "applying the chain rule. \n",
    "The computational algorithm for applying the chain rule\n",
    "in this fashion is called *backpropagation*.\n",
    "\n",
    "While autograd libraries have become\n",
    "a hot concern over the past decade,\n",
    "they have a long history. \n",
    "In fact the earliest references to autograd\n",
    "date back over half of a century :cite:`Wengert.1964`.\n",
    "The core ideas behind modern backpropagation\n",
    "date to a PhD thesis from 1980 :cite:`Speelpenning.1980`\n",
    "and were further developed in the late 1980s :cite:`Griewank.1989`.\n",
    "While backpropagation has become the default method \n",
    "for computing gradients, it is not the only option. \n",
    "For instance, the Julia programming language employs \n",
    "forward propagation :cite:`Revels.Lubin.Papamarkou.2016`. \n",
    "Before exploring methods, \n",
    "let's first master the autograd package.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "130439cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:08.286501Z",
     "iopub.status.busy": "2023-08-18T19:26:08.285693Z",
     "iopub.status.idle": "2023-08-18T19:26:10.052257Z",
     "shell.execute_reply": "2023-08-18T19:26:10.050994Z"
    },
    "origin_pos": 3,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2ab3850",
   "metadata": {
    "origin_pos": 6
   },
   "source": [
    "## A Simple Function\n",
    "\n",
    "Let's assume that we are interested\n",
    "in (**differentiating the function\n",
    "$y = 2\\mathbf{x}^{\\top}\\mathbf{x}$\n",
    "with respect to the column vector $\\mathbf{x}$.**)\n",
    "To start, we assign `x` an initial value.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4253cfab",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "7"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.056833Z",
     "iopub.status.busy": "2023-08-18T19:26:10.055871Z",
     "iopub.status.idle": "2023-08-18T19:26:10.084858Z",
     "shell.execute_reply": "2023-08-18T19:26:10.083727Z"
    },
    "origin_pos": 8,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0., 1., 2., 3.])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.arange(4.0)\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e75614b0",
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[**Before we calculate the gradient\n",
    "of $y$ with respect to $\\mathbf{x}$,\n",
    "we need a place to store it.**]\n",
    "In general, we avoid allocating new memory\n",
    "every time we take a derivative \n",
    "because deep learning requires \n",
    "successively computing derivatives\n",
    "with respect to the same parameters\n",
    "a great many times,\n",
    "and we might risk running out of memory.\n",
    "Note that the gradient of a scalar-valued function\n",
    "with respect to a vector $\\mathbf{x}$\n",
    "is vector-valued with \n",
    "the same shape as $\\mathbf{x}$.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2a001d1e",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.088716Z",
     "iopub.status.busy": "2023-08-18T19:26:10.087816Z",
     "iopub.status.idle": "2023-08-18T19:26:10.092878Z",
     "shell.execute_reply": "2023-08-18T19:26:10.091740Z"
    },
    "origin_pos": 13,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "# Can also create x = torch.arange(4.0, requires_grad=True)\n",
    "x.requires_grad_(True)\n",
    "x.grad  # The gradient is None by default"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e74bc02",
   "metadata": {
    "origin_pos": 15
   },
   "source": [
    "(**We now calculate our function of `x` and assign the result to `y`.**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6e3bd777",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "11"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.096336Z",
     "iopub.status.busy": "2023-08-18T19:26:10.095772Z",
     "iopub.status.idle": "2023-08-18T19:26:10.105236Z",
     "shell.execute_reply": "2023-08-18T19:26:10.104075Z"
    },
    "origin_pos": 17,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(28., grad_fn=<MulBackward0>)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y = 2 * torch.dot(x, x)\n",
    "y"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3067490",
   "metadata": {
    "origin_pos": 21,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[**We can now take the gradient of `y`\n",
    "with respect to `x`**] by calling \n",
    "its `backward` method.\n",
    "Next, we can access the gradient \n",
    "via `x`'s `grad` attribute.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "21b134ae",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "12"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.108600Z",
     "iopub.status.busy": "2023-08-18T19:26:10.108011Z",
     "iopub.status.idle": "2023-08-18T19:26:10.160854Z",
     "shell.execute_reply": "2023-08-18T19:26:10.159702Z"
    },
    "origin_pos": 25,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([ 0.,  4.,  8., 12.])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y.backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17d1390b",
   "metadata": {
    "origin_pos": 28
   },
   "source": [
    "(**We already know that the gradient of the function $y = 2\\mathbf{x}^{\\top}\\mathbf{x}$\n",
    "with respect to $\\mathbf{x}$ should be $4\\mathbf{x}$.**)\n",
    "We can now verify that the automatic gradient computation\n",
    "and the expected result are identical.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5030e37d",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "14"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.164665Z",
     "iopub.status.busy": "2023-08-18T19:26:10.163930Z",
     "iopub.status.idle": "2023-08-18T19:26:10.171033Z",
     "shell.execute_reply": "2023-08-18T19:26:10.169923Z"
    },
    "origin_pos": 30,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad == 4 * x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da440e48",
   "metadata": {
    "origin_pos": 34,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[**Now let's calculate \n",
    "another function of `x`\n",
    "and take its gradient.**]\n",
    "Note that PyTorch does not automatically \n",
    "reset the gradient buffer \n",
    "when we record a new gradient. \n",
    "Instead, the new gradient\n",
    "is added to the already-stored gradient.\n",
    "This behavior comes in handy\n",
    "when we want to optimize the sum \n",
    "of multiple objective functions.\n",
    "To reset the gradient buffer,\n",
    "we can call `x.grad.zero_()` as follows:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "add5cf4b",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "20"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.174691Z",
     "iopub.status.busy": "2023-08-18T19:26:10.173957Z",
     "iopub.status.idle": "2023-08-18T19:26:10.181847Z",
     "shell.execute_reply": "2023-08-18T19:26:10.180759Z"
    },
    "origin_pos": 37,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([1., 1., 1., 1.])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad.zero_()  # Reset the gradient\n",
    "y = x.sum()\n",
    "y.backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8bdd4c0c",
   "metadata": {
    "origin_pos": 40
   },
   "source": [
    "## Backward for Non-Scalar Variables\n",
    "\n",
    "When `y` is a vector, \n",
    "the most natural representation \n",
    "of the derivative of  `y`\n",
    "with respect to a vector `x` \n",
    "is a matrix called the *Jacobian*\n",
    "that contains the partial derivatives\n",
    "of each component of `y` \n",
    "with respect to each component of `x`.\n",
    "Likewise, for higher-order `y` and `x`,\n",
    "the result of differentiation could be an even higher-order tensor.\n",
    "\n",
    "While Jacobians do show up in some\n",
    "advanced machine learning techniques,\n",
    "more commonly we want to sum up \n",
    "the gradients of each component of `y`\n",
    "with respect to the full vector `x`,\n",
    "yielding a vector of the same shape as `x`.\n",
    "For example, we often have a vector \n",
    "representing the value of our loss function\n",
    "calculated separately for each example among\n",
    "a *batch* of training examples.\n",
    "Here, we just want to (**sum up the gradients\n",
    "computed individually for each example**).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9dda7124",
   "metadata": {
    "origin_pos": 42,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "Because deep learning frameworks vary \n",
    "in how they interpret gradients of\n",
    "non-scalar tensors,\n",
    "PyTorch takes some steps to avoid confusion.\n",
    "Invoking `backward` on a non-scalar elicits an error \n",
    "unless we tell PyTorch how to reduce the object to a scalar. \n",
    "More formally, we need to provide some vector $\\mathbf{v}$ \n",
    "such that `backward` will compute \n",
    "$\\mathbf{v}^\\top \\partial_{\\mathbf{x}} \\mathbf{y}$ \n",
    "rather than $\\partial_{\\mathbf{x}} \\mathbf{y}$. \n",
    "This next part may be confusing,\n",
    "but for reasons that will become clear later, \n",
    "this argument (representing $\\mathbf{v}$) is named `gradient`. \n",
    "For a more detailed description, see Yang Zhang's \n",
    "[Medium post](https://zhang-yang.medium.com/the-gradient-argument-in-pytorchs-backward-function-explained-by-examples-68f266950c29).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1baa40bd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.185096Z",
     "iopub.status.busy": "2023-08-18T19:26:10.184685Z",
     "iopub.status.idle": "2023-08-18T19:26:10.192537Z",
     "shell.execute_reply": "2023-08-18T19:26:10.191435Z"
    },
    "origin_pos": 45,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0., 2., 4., 6.])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad.zero_()\n",
    "y = x * x\n",
    "y.backward(gradient=torch.ones(len(y)))  # Faster: y.sum().backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffbd2c9d",
   "metadata": {
    "origin_pos": 48
   },
   "source": [
    "## Detaching Computation\n",
    "\n",
    "Sometimes, we wish to [**move some calculations\n",
    "outside of the recorded computational graph.**]\n",
    "For example, say that we use the input \n",
    "to create some auxiliary intermediate terms \n",
    "for which we do not want to compute a gradient. \n",
    "In this case, we need to *detach* \n",
    "the respective computational graph\n",
    "from the final result. \n",
    "The following toy example makes this clearer: \n",
    "suppose we have `z = x * y` and `y = x * x` \n",
    "but we want to focus on the *direct* influence of `x` on `z` \n",
    "rather than the influence conveyed via `y`. \n",
    "In this case, we can create a new variable `u`\n",
    "that takes the same value as `y` \n",
    "but whose *provenance* (how it was created)\n",
    "has been wiped out.\n",
    "Thus `u` has no ancestors in the graph\n",
    "and gradients do not flow through `u` to `x`.\n",
    "For example, taking the gradient of `z = x * u`\n",
    "will yield the result `u`,\n",
    "(not `3 * x * x` as you might have \n",
    "expected since `z = x * x * x`).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "107ac041",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "21"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.196001Z",
     "iopub.status.busy": "2023-08-18T19:26:10.195456Z",
     "iopub.status.idle": "2023-08-18T19:26:10.203246Z",
     "shell.execute_reply": "2023-08-18T19:26:10.202155Z"
    },
    "origin_pos": 50,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad.zero_()\n",
    "y = x * x\n",
    "u = y.detach()\n",
    "z = u * x\n",
    "\n",
    "z.sum().backward()\n",
    "x.grad == u"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0378e1f",
   "metadata": {
    "origin_pos": 53
   },
   "source": [
    "Note that while this procedure\n",
    "detaches `y`'s ancestors\n",
    "from the graph leading to `z`, \n",
    "the computational graph leading to `y` \n",
    "persists and thus we can calculate\n",
    "the gradient of `y` with respect to `x`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "cb8c674b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.206880Z",
     "iopub.status.busy": "2023-08-18T19:26:10.206001Z",
     "iopub.status.idle": "2023-08-18T19:26:10.213592Z",
     "shell.execute_reply": "2023-08-18T19:26:10.212476Z"
    },
    "origin_pos": 55,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad.zero_()\n",
    "y.sum().backward()\n",
    "x.grad == 2 * x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76f056ce",
   "metadata": {
    "origin_pos": 58
   },
   "source": [
    "## Gradients and Python Control Flow\n",
    "\n",
    "So far we reviewed cases where the path from input to output \n",
    "was well defined via a function such as `z = x * x * x`.\n",
    "Programming offers us a lot more freedom in how we compute results. \n",
    "For instance, we can make them depend on auxiliary variables \n",
    "or condition choices on intermediate results. \n",
    "One benefit of using automatic differentiation\n",
    "is that [**even if**] building the computational graph of \n",
    "(**a function required passing through a maze of Python control flow**)\n",
    "(e.g., conditionals, loops, and arbitrary function calls),\n",
    "(**we can still calculate the gradient of the resulting variable.**)\n",
    "To illustrate this, consider the following code snippet where \n",
    "the number of iterations of the `while` loop\n",
    "and the evaluation of the `if` statement\n",
    "both depend on the value of the input `a`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a83327c2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.218214Z",
     "iopub.status.busy": "2023-08-18T19:26:10.217554Z",
     "iopub.status.idle": "2023-08-18T19:26:10.222956Z",
     "shell.execute_reply": "2023-08-18T19:26:10.221858Z"
    },
    "origin_pos": 60,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def f(a):\n",
    "    b = a * 2\n",
    "    while b.norm() < 1000:\n",
    "        b = b * 2\n",
    "    if b.sum() > 0:\n",
    "        c = b\n",
    "    else:\n",
    "        c = 100 * b\n",
    "    return c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "189f6785",
   "metadata": {
    "origin_pos": 63
   },
   "source": [
    "Below, we call this function, passing in a random value, as input.\n",
    "Since the input is a random variable, \n",
    "we do not know what form \n",
    "the computational graph will take.\n",
    "However, whenever we execute `f(a)` \n",
    "on a specific input, we realize \n",
    "a specific computational graph\n",
    "and can subsequently run `backward`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c5ef0264",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.227364Z",
     "iopub.status.busy": "2023-08-18T19:26:10.226919Z",
     "iopub.status.idle": "2023-08-18T19:26:10.232880Z",
     "shell.execute_reply": "2023-08-18T19:26:10.231773Z"
    },
    "origin_pos": 65,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "a = torch.randn(size=(), requires_grad=True)\n",
    "d = f(a)\n",
    "d.backward()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51065133",
   "metadata": {
    "origin_pos": 68
   },
   "source": [
    "Even though our function `f` is, for demonstration purposes, a bit contrived,\n",
    "its dependence on the input is quite simple: \n",
    "it is a *linear* function of `a` \n",
    "with piecewise defined scale. \n",
    "As such, `f(a) / a` is a vector of constant entries \n",
    "and, moreover, `f(a) / a` needs to match \n",
    "the gradient of `f(a)` with respect to `a`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ab14ef91",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:26:10.237298Z",
     "iopub.status.busy": "2023-08-18T19:26:10.236886Z",
     "iopub.status.idle": "2023-08-18T19:26:10.243577Z",
     "shell.execute_reply": "2023-08-18T19:26:10.242480Z"
    },
    "origin_pos": 70,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(True)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.grad == d / a"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a992f28c",
   "metadata": {
    "origin_pos": 73
   },
   "source": [
    "Dynamic control flow is very common in deep learning. \n",
    "For instance, when processing text, the computational graph\n",
    "depends on the length of the input. \n",
    "In these cases, automatic differentiation \n",
    "becomes vital for statistical modeling \n",
    "since it is impossible to compute the gradient *a priori*. \n",
    "\n",
    "## Discussion\n",
    "\n",
    "You have now gotten a taste of the power of automatic differentiation. \n",
    "The development of libraries for calculating derivatives\n",
    "both automatically and efficiently \n",
    "has been a massive productivity booster\n",
    "for deep learning practitioners,\n",
    "liberating them so they can focus on less menial.\n",
    "Moreover, autograd lets us design massive models\n",
    "for which pen and paper gradient computations \n",
    "would be prohibitively time consuming.\n",
    "Interestingly, while we use autograd to *optimize* models\n",
    "(in a statistical sense)\n",
    "the *optimization* of autograd libraries themselves\n",
    "(in a computational sense)\n",
    "is a rich subject\n",
    "of vital interest to framework designers.\n",
    "Here, tools from compilers and graph manipulation \n",
    "are leveraged to compute results \n",
    "in the most expedient and memory-efficient manner. \n",
    "\n",
    "For now, try to remember these basics: (i) attach gradients to those variables with respect to which we desire derivatives; (ii) record the computation of the target value; (iii) execute the backpropagation function; and  (iv) access the resulting gradient.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Why is the second derivative much more expensive to compute than the first derivative?\n",
    "1. After running the function for backpropagation, immediately run it again and see what happens. Investigate.\n",
    "1. In the control flow example where we calculate the derivative of `d` with respect to `a`, what would happen if we changed the variable `a` to a random vector or a matrix? At this point, the result of the calculation `f(a)` is no longer a scalar. What happens to the result? How do we analyze this?\n",
    "1. Let $f(x) = \\sin(x)$. Plot the graph of $f$ and of its derivative $f'$. Do not exploit the fact that $f'(x) = \\cos(x)$ but rather use automatic differentiation to get the result. \n",
    "1. Let $f(x) = ((\\log x^2) \\cdot \\sin x) + x^{-1}$. Write out a dependency graph tracing results from $x$ to $f(x)$. \n",
    "1. Use the chain rule to compute the derivative $\\frac{df}{dx}$ of the aforementioned function, placing each term on the dependency graph that you constructed previously. \n",
    "1. Given the graph and the intermediate derivative results, you have a number of options when computing the gradient. Evaluate the result once starting from $x$ to $f$ and once from $f$ tracing back to $x$. The path from $x$ to $f$ is commonly known as *forward differentiation*, whereas the path from $f$ to $x$ is known as backward differentiation. \n",
    "1. When might you want to use forward, and when backward, differentiation? Hint: consider the amount of intermediate data needed, the ability to parallelize steps, and the size of matrices and vectors involved.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c0ab97d",
   "metadata": {
    "origin_pos": 75,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/35)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}